<?php
   class Pay_result extends MY_Controller{
	   public function __construct(){
		   parent::__construct();
		   $this->load->helper("url");
		   $this->load->model("model_pay");
		   $this->load->library('session');
	   }
	   public function index(){
		   // Define Constants
			$SECURE_SECRET = "A3EFDFABA8653DF2342E8DAC29B51AF0";
			// Check $_GET haanhdon
			if(!isset($_GET['vpc_SecureHash'])){ $_GET['vpc_SecureHash'] = "";}
			if(!isset($_GET['vpc_TxnResponseCode'])){ $_GET['vpc_TxnResponseCode'] = "";}
			if(!isset($_GET['vpc_Amount'])){ $_GET['vpc_Amount'] = "";}
			if(!isset($_GET['vpc_Locale'])){ $_GET['vpc_Locale'] = "";}
			if(!isset($_GET['vpc_Command'])){ $_GET['vpc_Command'] = "";}
			if(!isset($_GET['vpc_Version'])){ $_GET['vpc_Version'] = "";}
			if(!isset($_GET['vpc_OrderInfo'])){ $_GET['vpc_OrderInfo'] = "";}
			if(!isset($_GET['vpc_Merchant'])){ $_GET['vpc_Merchant'] = "";}
			if(!isset($_GET['vpc_MerchTxnRef'])){ $_GET['vpc_MerchTxnRef'] = "";}
			if(!isset($_GET['vpc_TransactionNo'])){ $_GET['vpc_TransactionNo'] = "";}
			//If there has been a merchant secret set then sort and loop through all the
			$vpc_Txn_Secure_Hash = $_GET ["vpc_SecureHash"];
			unset ( $_GET ["vpc_SecureHash"] );
			
			// set a flag to indicate if hash has been validated
			$errorExists = false;
			
			if (strlen ( $SECURE_SECRET ) > 0 && $_GET ["vpc_TxnResponseCode"] != "7" && $_GET ["vpc_TxnResponseCode"] != "No Value Returned") {
				
				//$stringHashData = $SECURE_SECRET;
				//*****************************khởi tạo chuỗi mã hóa rỗng*****************************
				$stringHashData = "";
				
				// sort all the incoming vpc response fields and leave out any with no value
				foreach ( $_GET as $key => $value ) {
			//        if ($key != "vpc_SecureHash" or strlen($value) > 0) {
			//            $stringHashData .= $value;
			//        }
			//      *****************************chỉ lấy các tham số bắt đầu bằng "vpc_" hoặc "user_" và khác trống và không phải chuỗi hash code trả về*****************************
					if ($key != "vpc_SecureHash" && (strlen($value) > 0) && ((substr($key, 0,4)=="vpc_") || (substr($key,0,5) =="user_"))) {
						$stringHashData .= $key . "=" . $value . "&";
					}
				}
			//  *****************************Xóa dấu & thừa cuối chuỗi dữ liệu*****************************
				$stringHashData = rtrim($stringHashData, "&");	
				
				
			//    if (strtoupper ( $vpc_Txn_Secure_Hash ) == strtoupper ( md5 ( $stringHashData ) )) {
			//    *****************************Thay hàm tạo chuỗi mã hóa*****************************
				if (strtoupper ( $vpc_Txn_Secure_Hash ) == strtoupper(hash_hmac('SHA256', $stringHashData, pack('H*',$SECURE_SECRET)))) {
					// Secure Hash validation succeeded, add a data field to be displayed
					// later.
					$hashValidated = "CORRECT";
				} else {
					// Secure Hash validation failed, add a data field to be displayed
					// later.
					$hashValidated = "INVALID HASH";
				}
			} else {
				// Secure Hash was not validated, add a data field to be displayed later.
				$hashValidated = "INVALID HASH";
			}
			
			// Define Variables
			// ----------------
			// Extract the available receipt fields from the VPC Response
			// If not present then let the value be equal to 'No Value Returned'
			// Standard Receipt Data
			$amount = $this->null2unknown($_GET ["vpc_Amount"] );
			$locale = $this->null2unknown( $_GET ["vpc_Locale"] );
			//$batchNo = null2unknown ( $_GET ["vpc_BatchNo"] );
			$command = $this->null2unknown( $_GET ["vpc_Command"] );
			//$message = $this->null2unknown ( $_GET ["vpc_Message"] );
			$version = $this->null2unknown( $_GET ["vpc_Version"] );
			//$cardType = null2unknown ( $_GET ["vpc_Card"] );
			$orderInfo = $this->null2unknown( $_GET ["vpc_OrderInfo"] );
			//$receiptNo = null2unknown ( $_GET ["vpc_ReceiptNo"] );
			$merchantID = $this->null2unknown( $_GET ["vpc_Merchant"] );
			//$authorizeID = null2unknown ( $_GET ["vpc_AuthorizeId"] );
			$merchTxnRef = $this->null2unknown( $_GET ["vpc_MerchTxnRef"] );
			$transactionNo = $this->null2unknown( $_GET ["vpc_TransactionNo"] );
			//$acqResponseCode = null2unknown ( $_GET ["vpc_AcqResponseCode"] );
			$txnResponseCode = $this->null2unknown( $_GET ["vpc_TxnResponseCode"] );
			
			// status 
			$transStatus = "";
			if($hashValidated=="CORRECT" && $txnResponseCode=="0"){
				$transStatus = "Giao dịch thành công";
				$status = 1;
			}elseif ($hashValidated=="INVALID HASH" && $txnResponseCode=="0"){
				$transStatus = "Giao dịch Pendding";
				$status = 2;
			}else {
				$transStatus = "Giao dịch thất bại";
				$status = 3;
			}
			$order_id 	= $this->session->userdata("order");
			$type 		= $this->session->userdata("type");
			$startdate 	= $this->session->userdata("startdate");
			$startmont	= $this->session->userdata("startmont");
			$room_now	= $this->session->userdata("room_now");
			$room_next	= $this->session->userdata("room_next");
			$room_num	= $this->session->userdata("room_num");
			$room_tick  = $this->session->userdata("room_tick");
			if(!$order_id){
				redirect(base_url());
			}
			echo "Order_id ".$order_id."<br />";
			echo "Type ".$type."<br />";
			echo "Start month : ".$startmont." <br />";
			echo "Start date : ".$startdate."<br />";
			echo "Room : ".$room_num."<br />";
			echo "Room now : ".$room_now."<br />";
			echo "Room next: ".$room_next."<br />";
			echo "Số vé : ".$room_tick;
			die();
			$tomorrow  = mktime(0, 0, 0, $startmont , $startdate+1, date("Y"));
			$date1 = date("j",$tomorrow);
			$date2 = date("n",$tomorrow);
			if($date1 < 10){
				$date1 = "0".$date1;
			}
			if($date2 < 10){
				$date2 = "0".$date2;
			}
			$next_day = $date1;
			$next_mon = $date2;
			//echo $next_mon;
			if($status == 1){ // thanh toán thành công
				$room_now 	= $room_now - $room_num;
				$update_order = array(
					"order_status" => "1"
				);
				$update_day_now = array(
					"day_month".abs($startmont) => $room_now
				);
				$this->model_pay->update_room($update_day_now,abs($startdate));
				$this->model_pay->update_order($update_order,$order_id);
				//$this->debug($update_day_now);
			}
			$data['value'] = array(
				"trans_id" => $merchTxnRef,
				"trans_info" => $orderInfo,
				"trans_price" => $amount,
				"trans_result" => $txnResponseCode
			);
			$data['title']	= "Trạng thái giao dịch";
			$data['status'] = $transStatus;
			$data['pay_status']	=  $this->getResponseDescription($txnResponseCode);
			$this->load->view("payment/result/status",$data);
	   }
	   public function goldtime(){
		   // Define Constants
			$SECURE_SECRET = "A3EFDFABA8653DF2342E8DAC29B51AF0";
			// Check $_GET haanhdon
			if(!isset($_GET['vpc_SecureHash'])){ $_GET['vpc_SecureHash'] = "";}
			if(!isset($_GET['vpc_TxnResponseCode'])){ $_GET['vpc_TxnResponseCode'] = "";}
			if(!isset($_GET['vpc_Amount'])){ $_GET['vpc_Amount'] = "";}
			if(!isset($_GET['vpc_Locale'])){ $_GET['vpc_Locale'] = "";}
			if(!isset($_GET['vpc_Command'])){ $_GET['vpc_Command'] = "";}
			if(!isset($_GET['vpc_Version'])){ $_GET['vpc_Version'] = "";}
			if(!isset($_GET['vpc_OrderInfo'])){ $_GET['vpc_OrderInfo'] = "";}
			if(!isset($_GET['vpc_Merchant'])){ $_GET['vpc_Merchant'] = "";}
			if(!isset($_GET['vpc_MerchTxnRef'])){ $_GET['vpc_MerchTxnRef'] = "";}
			if(!isset($_GET['vpc_TransactionNo'])){ $_GET['vpc_TransactionNo'] = "";}
			//If there has been a merchant secret set then sort and loop through all the
			$vpc_Txn_Secure_Hash = $_GET ["vpc_SecureHash"];
			unset ( $_GET ["vpc_SecureHash"] );
			
			// set a flag to indicate if hash has been validated
			$errorExists = false;
			
			if (strlen ( $SECURE_SECRET ) > 0 && $_GET ["vpc_TxnResponseCode"] != "7" && $_GET ["vpc_TxnResponseCode"] != "No Value Returned") {
				
				//$stringHashData = $SECURE_SECRET;
				//*****************************khởi tạo chuỗi mã hóa rỗng*****************************
				$stringHashData = "";
				
				// sort all the incoming vpc response fields and leave out any with no value
				foreach ( $_GET as $key => $value ) {
			//        if ($key != "vpc_SecureHash" or strlen($value) > 0) {
			//            $stringHashData .= $value;
			//        }
			//      *****************************chỉ lấy các tham số bắt đầu bằng "vpc_" hoặc "user_" và khác trống và không phải chuỗi hash code trả về*****************************
					if ($key != "vpc_SecureHash" && (strlen($value) > 0) && ((substr($key, 0,4)=="vpc_") || (substr($key,0,5) =="user_"))) {
						$stringHashData .= $key . "=" . $value . "&";
					}
				}
			//  *****************************Xóa dấu & thừa cuối chuỗi dữ liệu*****************************
				$stringHashData = rtrim($stringHashData, "&");	
				
				
			//    if (strtoupper ( $vpc_Txn_Secure_Hash ) == strtoupper ( md5 ( $stringHashData ) )) {
			//    *****************************Thay hàm tạo chuỗi mã hóa*****************************
				if (strtoupper ( $vpc_Txn_Secure_Hash ) == strtoupper(hash_hmac('SHA256', $stringHashData, pack('H*',$SECURE_SECRET)))) {
					// Secure Hash validation succeeded, add a data field to be displayed
					// later.
					$hashValidated = "CORRECT";
				} else {
					// Secure Hash validation failed, add a data field to be displayed
					// later.
					$hashValidated = "INVALID HASH";
				}
			} else {
				// Secure Hash was not validated, add a data field to be displayed later.
				$hashValidated = "INVALID HASH";
			}
			
			// Define Variables
			// ----------------
			// Extract the available receipt fields from the VPC Response
			// If not present then let the value be equal to 'No Value Returned'
			// Standard Receipt Data
			$amount = $this->null2unknown($_GET ["vpc_Amount"] );
			$locale = $this->null2unknown( $_GET ["vpc_Locale"] );
			//$batchNo = null2unknown ( $_GET ["vpc_BatchNo"] );
			$command = $this->null2unknown( $_GET ["vpc_Command"] );
			//$message = $this->null2unknown ( $_GET ["vpc_Message"] );
			$version = $this->null2unknown( $_GET ["vpc_Version"] );
			//$cardType = null2unknown ( $_GET ["vpc_Card"] );
			$orderInfo = $this->null2unknown( $_GET ["vpc_OrderInfo"] );
			//$receiptNo = null2unknown ( $_GET ["vpc_ReceiptNo"] );
			$merchantID = $this->null2unknown( $_GET ["vpc_Merchant"] );
			//$authorizeID = null2unknown ( $_GET ["vpc_AuthorizeId"] );
			$merchTxnRef = $this->null2unknown( $_GET ["vpc_MerchTxnRef"] );
			$transactionNo = $this->null2unknown( $_GET ["vpc_TransactionNo"] );
			//$acqResponseCode = null2unknown ( $_GET ["vpc_AcqResponseCode"] );
			$txnResponseCode = $this->null2unknown( $_GET ["vpc_TxnResponseCode"] );
			
			// status 
			$transStatus = "";
			if($hashValidated=="CORRECT" && $txnResponseCode=="0"){
				$transStatus = "Giao dịch thành công";
				$status = 1;
			}elseif ($hashValidated=="INVALID HASH" && $txnResponseCode=="0"){
				$transStatus = "Giao dịch Pendding";
				$status = 2;
			}else {
				$transStatus = "Giao dịch thất bại";
				$status = 3;
			}
			$order_id 	= $this->session->userdata("order");
			$type 		= $this->session->userdata("type");
			$startdate 	= $this->session->userdata("startdate");
			$startmont	= $this->session->userdata("startmont");
			$room_now	= $this->session->userdata("room_now");
			$room_next	= $this->session->userdata("room_next");
			$room_num	= $this->session->userdata("room_num");
			$gold_total = $this->session->userdata("gold_total");
			$gold    	= $this->session->userdata("gold_type");
			$gold_recod = ($this->model_pay->count_gold($gold)+1);
			//echo "tổng số ban đầu : ".$gold_total."<br />";
			//echo "gold type : ".$gold."<br />";
			//echo "Số người đã đăng ký : ".$gold_recod;
			
			//$this->debug($gold_time)*/;
			if(!$order_id || !$gold){
				redirect(base_url()."home/payment/failed");
			}
			$tomorrow  = mktime(0, 0, 0, $startmont , $startdate+1, date("Y"));
			$date1 = date("j",$tomorrow);
			$date2 = date("n",$tomorrow);
			if($date1 < 10){
				$date1 = "0".$date1;
			}
			if($date2 < 10){
				$date2 = "0".$date2;
			}
			$next_day = $date1;
			$next_mon = $date2;
			if($status == 1){ // thanh toán thành công
				$room_now 	= $room_now - $room_num;
				$room_next  = $room_next - $room_num;
				$goldtime = $gold_total - $gold_recod;
				//echo "<br /> còn lại ".$goldtime;
				$update_order = array(
					"order_status" => "1"
				);
				$update_goldtime = array(
					"gold_type".$gold => $goldtime
				);
				$this->model_pay->update_goldtime($update_goldtime,"1");
				if($type == 2){ // 3 ngày 2 đêm
					$update_day_now = array(
						"day_month".abs($startmont) => $room_now
					);
					$update_day_next = array(
						"day_month".abs($next_mon) => $room_next,
					);
					//$this->debug($update_day_next);
					$this->model_pay->update_room($update_day_now,abs($startdate)); // update room now
					$this->model_pay->update_room($update_day_next,abs($next_day)); // update room next
				}else{ // 2 ngày 1 đêm
					$update_day_now = array(
						"day_month".abs($startmont) => $room_now
					);
					$this->model_pay->update_room($update_day_now,abs($startdate));
				}
				$this->model_pay->update_gold_order($update_order,$order_id);
				//$this->debug($update_day_now);
			}
			$data['value'] = array(
				"trans_id" => $merchTxnRef,
				"trans_info" => $orderInfo,
				"trans_price" => $amount,
				"trans_result" => $txnResponseCode
			);
			$data['title']	= "Trạng thái giao dịch";
			$data['status'] = $transStatus;
			$data['pay_status']	=  $this->getResponseDescription($txnResponseCode);
			$this->load->view("payment/result/status",$data);
	   }
	   public function null2unknown($data) {
			if ($data == "") {
				return "Không có kết quả trả về";
			} else {
				return $data;
			}
		}
		public function getResponseDescription($responseCode) {
			switch ($responseCode) {
				case "0" :
					$result = "Giao dịch thành công - Approved";
					break;
				case "1" :
					$result = "Ngân hàng từ chối giao dịch - Bank Declined";
					break;
				case "3" :
					$result = "Mã đơn vị không tồn tại - Merchant not exist";
					break;
				case "4" :
					$result = "Không đúng access code - Invalid access code";
					break;
				case "5" :
					$result = "Số tiền không hợp lệ - Invalid amount";
					break;
				case "6" :
					$result = "Mã tiền tệ không tồn tại - Invalid currency code";
					break;
				case "7" :
					$result = "Lỗi không xác định - Unspecified Failure ";
					break;
				case "8" :
					$result = "Số thẻ không đúng - Invalid card Number";
					break;
				case "9" :
					$result = "Tên chủ thẻ không đúng - Invalid card name";
					break;
				case "10" :
					$result = "Thẻ hết hạn/Thẻ bị khóa - Expired Card";
					break;
				case "11" :
					$result = "Thẻ chưa đăng ký sử dụng dịch vụ - Card Not Registed Service(internet banking)";
					break;
				case "12" :
					$result = "Ngày phát hành/Hết hạn không đúng - Invalid card date";
					break;
				case "13" :
					$result = "Vượt quá hạn mức thanh toán - Exist Amount";
					break;
				case "21" :
					$result = "Số tiền không đủ để thanh toán - Insufficient fund";
					break;
				case "99" :
					$result = "Người sủ dụng hủy giao dịch - User cancel";
					break;
				default :
					$result = "Giao dịch thất bại - Failured";
			}
			return $result;
		}
   }